<?php
/**
 * Created by PhpStorm.
 * UsersF: Mloong
 * Date: 2018/12/12
 * Time: 14:27
 */

namespace Page;
use \think\Controller;
use think\Exception;

class Page
{
    /**
     * @var Controller 初始化控制器
     * @var model 初始化模型
     * @var int $page 页数
     * @var int $limit 每页的数量
     * @var array $data 显示或隐藏的数据
     * @var array $condition 排序
     * @var array $where 查询条件
     * @var boolean $boolean true为显示，false为隐藏
     */
    private $model;
    private $page;
    private $limit;
    private $data = [];
    private $order;
    private $where;
    private $count;
    public function __construct($model, $page, $limit, $data = [], $order = null,$where=null)
    {
        $this->model = $model;
        $this->page = $page;
        $this->limit = $limit;
        $this->data = $data;
        $this->order = $order;
        $this->where = $where;
    }

    /**@var code 状态码
     * @var data 数据
     * @var count 总条数
     * @return array
     */
    public function layuiPage()
    {
        $data =$this->getPageData();
        try{
            $list = $data->toArray();
        }catch (\Exception $e){
            $list = 0;
        }
        $count = $this->getCount();
        return [
           'code' => 0,
           'data' => $list,
            'count' => $this->count
        ];
    }

    public function layuiPageStatus()
    {
        $data =$this->getPageData();
        try{
            $list = $data->toArray();
        }catch (\Exception $e){
            $list = 0;
        }
        $count = $this->getCount();
        return [
            'code' => 0,
            'data' => $list,
            'count' => $this->count
        ];
    }

    /**
     * @return mixed 数据包所有的条数
     */
    private function getCount()
    {
        $count = $this->model->count();
        return $count;
    }

    /**
     * @return mixed 返回选择页面的数据
     */
    private function getPageData()
    {
        $fun = null;
        // 判断$data是否为空
        //为空则显示全部，不为空则显示数组里面的字段
        if($this->data){
            $fun = 'visible';
        }else{
            $fun = 'hidden';
        }
            $data = $this->model->where($this->where)
                ->order($this->order)
                ->{$fun}($this->data);
            $this->count = $data->count();
        return $data->page($this->page, $this->limit)
            ->select();
    }
}